<template>
	<view class="container">
		<!-- 商品图片轮播 -->
		<swiper class="product-swiper" circular indicator-dots autoplay :interval="3000" :duration="500" indicator-active-color="#409EFF">
			<swiper-item v-for="(item, index) in commodity.image" :key="index">
				<image :src="getImgUrl(item)" mode="aspectFill" class="product-image"></image>
			</swiper-item>
			<swiper-item v-if="!commodity.image || commodity.image.length === 0">
				<view class="no-image">暂无图片</view>
			</swiper-item>
		</swiper>
		
		<!-- 商品信息 -->
		<view class="product-info">
			<view class="product-price">¥{{ commodity.price }}</view>
			<view class="product-name">{{ commodity.name }}</view>
			<view class="product-desc">{{ commodity.description || '暂无描述' }}</view>
			<view class="product-meta">
				<text>销量: {{ commodity.salesVolume || 0 }}</text>
				<text>库存: {{ commodity.stock || 0 }}</text>
			</view>
		</view>
		
		<!-- 商品详情 -->
		<view class="product-detail">
			<view class="detail-title">商品详情</view>
			<view class="detail-content">
				<rich-text :nodes="commodity.detail || '暂无详细信息'"></rich-text>
			</view>
		</view>
		
		<!-- 底部操作栏 -->
		<view class="action-bar">
			<view class="action-btn-group">
				<view class="action-icon" @click="goToHome">
					<text class="iconfont icon-home"></text>
					<text>首页</text>
				</view>
				<view class="action-icon" @click="goToCart">
					<text class="iconfont icon-cart"></text>
					<text>购物车</text>
				</view>
			</view>
			<view class="action-btn add-cart" @click="addToCart">加入购物车</view>
			<view class="action-btn buy-now" @click="buyNow">立即购买</view>
		</view>
	</view>
</template>

<script>
import http, { SERVER_BASE_URL } from '@/utils/request';

export default {
	data() {
		return {
			id: null,
			commodity: {},
			quantity: 1
		};
	},
	onLoad(options) {
		if (options.id) {
			this.id = options.id;
			this.fetchCommodityDetail();
		} else {
			uni.showToast({
				title: '商品ID不存在',
				icon: 'none'
			});
			setTimeout(() => {
				uni.navigateBack();
			}, 1500);
		}
	},
	methods: {
		// 获取商品详情
		async fetchCommodityDetail() {
			try {
				uni.showLoading({
					title: '加载中...'
				});
				
				const res = await http.get(`/commodities/${this.id}`);
				this.commodity = res || {};
				
				// 更新页面标题
				if (this.commodity.name) {
					uni.setNavigationBarTitle({
						title: this.commodity.name
					});
				}
			} catch (error) {
				console.error('获取商品详情失败', error);
				uni.showToast({
					title: '获取商品详情失败',
					icon: 'none'
				});
			} finally {
				uni.hideLoading();
			}
		},
		
		// 处理图片URL
		getImgUrl(url) {
			if (!url) return '';
			
			// 确保有服务器地址前缀
			let fullUrl = url;
			
			if (url.startsWith('/uploads/')) {
				fullUrl = SERVER_BASE_URL + url;
			}
			
			return fullUrl;
		},
		
		// 跳转到首页
		goToHome() {
			uni.switchTab({
				url: '/pages/index/index'
			});
		},
		
		// 跳转到购物车
		goToCart() {
			uni.switchTab({
				url: '/pages/cart/cart'
			});
		},
		
		// 加入购物车
		async addToCart() {
			if (!this.commodity.id) {
				uni.showToast({
					title: '商品信息不完整',
					icon: 'none'
				});
				return;
			}
			
			// 获取用户信息，从正确的存储键获取
			const userStr = uni.getStorageSync('user');
			let userInfo = null;
			
			if (userStr) {
				try {
					userInfo = JSON.parse(userStr);
				} catch (error) {
					console.error('解析用户信息失败', error);
				}
			}
			
			if (!userInfo || !userInfo.id) {
				uni.showToast({
					title: '请先登录',
					icon: 'none'
				});
				
				// 跳转到登录页面
				setTimeout(() => {
					uni.navigateTo({
						url: '/pages/login/login'
					});
				}, 1500);
				return;
			}
			
			try {
				uni.showLoading({
					title: '添加中...'
				});
				
				const cartData = {
					userId: userInfo.id,
					commodityId: this.commodity.id,
					quantity: this.quantity,
					selected: true
				};
				
				await http.post('/cart/add', cartData);
				
				uni.showToast({
					title: '添加成功',
					icon: 'success'
				});
			} catch (error) {
				console.error('添加购物车失败', error);
				uni.showToast({
					title: '添加购物车失败',
					icon: 'none'
				});
			} finally {
				uni.hideLoading();
			}
		},
		
		// 立即购买
		buyNow() {
			if (!this.commodity.id) {
				uni.showToast({
					title: '商品信息不完整',
					icon: 'none'
				});
				return;
			}
			
			// 获取用户信息，从正确的存储键获取
			const userStr = uni.getStorageSync('user');
			let userInfo = null;
			
			if (userStr) {
				try {
					userInfo = JSON.parse(userStr);
				} catch (error) {
					console.error('解析用户信息失败', error);
				}
			}
			
			if (!userInfo || !userInfo.id) {
				uni.showToast({
					title: '请先登录',
					icon: 'none'
				});
				
				// 跳转到登录页面
				setTimeout(() => {
					uni.navigateTo({
						url: '/pages/login/login'
					});
				}, 1500);
				return;
			}
			
			// 跳转到订单确认页面，传递商品信息
			uni.navigateTo({
				url: `/pages/order/confirm?commodityId=${this.commodity.id}&quantity=${this.quantity}`
			});
		}
	}
};
</script>

<style>
.container {
	padding-bottom: 100rpx; /* 为底部操作栏留出空间 */
	background-color: #f5f5f5;
}

/* 商品图片轮播 */
.product-swiper {
	width: 100%;
	height: 750rpx;
}

.product-image {
	width: 100%;
	height: 100%;
}

.no-image {
	width: 100%;
	height: 100%;
	display: flex;
	align-items: center;
	justify-content: center;
	background-color: #f5f5f5;
	color: #999;
	font-size: 28rpx;
}

/* 商品信息 */
.product-info {
	padding: 30rpx;
	background-color: #ffffff;
	margin-bottom: 20rpx;
}

.product-price {
	font-size: 40rpx;
	color: #ff6700;
	font-weight: bold;
	margin-bottom: 16rpx;
}

.product-name {
	font-size: 32rpx;
	color: #333;
	font-weight: bold;
	margin-bottom: 16rpx;
	line-height: 1.4;
}

.product-desc {
	font-size: 28rpx;
	color: #666;
	margin-bottom: 16rpx;
	line-height: 1.5;
}

.product-meta {
	display: flex;
	justify-content: space-between;
	font-size: 24rpx;
	color: #999;
}

/* 商品详情 */
.product-detail {
	padding: 30rpx;
	background-color: #ffffff;
}

.detail-title {
	font-size: 32rpx;
	color: #333;
	font-weight: bold;
	margin-bottom: 20rpx;
	position: relative;
	padding-left: 20rpx;
}

.detail-title::before {
	content: '';
	position: absolute;
	left: 0;
	top: 6rpx;
	width: 8rpx;
	height: 32rpx;
	background-color: #409EFF;
	border-radius: 4rpx;
}

.detail-content {
	font-size: 28rpx;
	color: #666;
	line-height: 1.6;
}

/* 底部操作栏 */
.action-bar {
	position: fixed;
	bottom: 0;
	left: 0;
	right: 0;
	height: 100rpx;
	background-color: #ffffff;
	display: flex;
	align-items: center;
	box-shadow: 0 -2rpx 10rpx rgba(0, 0, 0, 0.05);
	z-index: 100;
}

.action-btn-group {
	display: flex;
	width: 30%;
	height: 100%;
}

.action-icon {
	flex: 1;
	display: flex;
	flex-direction: column;
	align-items: center;
	justify-content: center;
	font-size: 20rpx;
	color: #666;
}

.action-icon .iconfont {
	font-size: 40rpx;
	margin-bottom: 4rpx;
}

.action-btn {
	flex: 1;
	height: 100%;
	display: flex;
	align-items: center;
	justify-content: center;
	font-size: 28rpx;
	color: #ffffff;
}

.add-cart {
	background-color: #ff9500;
}

.buy-now {
	background-color: #ff6700;
}
</style> 